package edu.columbia.aicheckers;

import edu.columbia.aicheckers.agent.IAgent;
import edu.columbia.aicheckers.model.BoardState;
import edu.columbia.aicheckers.model.Color;
import edu.columbia.aicheckers.model.Move;

public class CheckerGame {

	public static int STALEMATE_COUNT = 150;
	private BoardState currentState;
	IAgent white;
	IAgent black;
	private boolean isPrintDebugInfo = true;
	
	private enum Result
	{
		WhiteVictory,
		BlackVictory,
		Stalemate,
		Undetermined;
	}
	
	public void setPrintDebugInfo(boolean isSetPrintDebugInfo)
	{
		this.isPrintDebugInfo = isSetPrintDebugInfo;
	}
	
	public boolean getPrintDebugInfo()
	{
		return this.isPrintDebugInfo;
	}
	
	public void println(String s)
	{
		if(isPrintDebugInfo)
			System.out.println(s);
	}
	
	public CheckerGame(IAgent whiteAgent, IAgent blackAgent)
	{
		setBlackAgent(blackAgent);
		setWhiteAgent(whiteAgent);
	}
	
	public void setWhiteAgent(IAgent white)
	{
		this.white = white;
	}
	
	public void setBlackAgent(IAgent black)
	{
		this.black = black;
	}
	
	public Color start()
	{
		// New fresh board
		currentState = new BoardState();
		Color winner = Color.Empty;
		int turn = 1;
		println("Start of game");
		while(winner == Color.Empty)
		{
			println("Start of turn " + turn);
			// Do white ply
			winner = doPly(Color.White,white);
			if(winner != Color.Empty)
			{
				break;
			}
			// Do black ply
			winner = doPly(Color.Black,black);
			if(winner != Color.Empty)
			{
				break;
			}
			
			if(turn > STALEMATE_COUNT)
			{
				return Color.Empty;
			}
			
			// Finish turn
			println("End of turn " + turn);
			turn++;
		}
		println("Result - Winner is: " + winner);
		println("End of game");
		return winner;
	}
	
	private Color doPly(Color color, IAgent agent)
	{
		Move move = null;
		println(color.toString() + " agent ply");
		while(move == null || currentState.getCurrentPly() == color)
		{
			move = agent.doPly(currentState,color);
			if(move == null)
			{
				// No more moves left for this agent - other agent wins
				return Color.getOponnentColor(color);
			}
			 if(!currentState.applyMove(move))
			 {
					throw new IllegalArgumentException("White agent performed an illegal move!!!");
			 }
			 println(color.toString() + " agent moved: " + move.toString());
			 println(currentState.toString());
			 if (!currentState.hasCheckers(Color.getOponnentColor(color))) {
				return color;
			 }
		}
		return Color.Empty;
	}

	
	
}
